<script setup lang="ts">
import Iconify from '@/components/Iconify/index.vue';
import { approveAuditTask, getAuditTaskPage, rejectAuditTask } from '@/services/api/audit';
import { AuditType, TaskStatus } from '@/services/model/auditModel.d';
import { computed, onMounted, ref, watch } from 'vue';

onMounted(() => {
  fetchAuditList();
  const page = document.querySelector('.min-h-screen');
  if (page) {
    page.addEventListener('scroll', () => {
      if (page.scrollTop + page.clientHeight >= page.scrollHeight - 100) {
        loadMore();
      }
    });
  }
});

interface AuditItem {
  id: string
  type: AuditType
  title: string
  content: string
  author: string
  createTime: string
  status: TaskStatus
  avatar?: string
  rejectReason?: string
}

// 当前选中的审核类型
const activeTab = ref<AuditType>(AuditType.ARTICLE);
watch(activeTab, () => {
  fetchAuditList();
});

// 模拟审核数据
const auditList = ref<AuditItem[]>([]);

// 过滤当前类型的审核项
const filteredList = computed(() => {
  return auditList.value.filter(item => item.type === activeTab.value);
});

function formatTimeAgo(dateString: string) {
  const date = new Date(dateString);
  const now = new Date();
  const diffInSeconds = Math.floor((now.getTime() - date.getTime()) / 1000);

  if (diffInSeconds < 60)
    return '刚刚';
  if (diffInSeconds < 3600)
    return `${Math.floor(diffInSeconds / 60)}分钟前`;
  if (diffInSeconds < 86400)
    return `${Math.floor(diffInSeconds / 3600)}小时前`;
  if (diffInSeconds < 2592000)
    return `${Math.floor(diffInSeconds / 86400)}天前`;
  return `${Math.floor(diffInSeconds / 2592000)}个月前`;
}

function truncateContent(content: string, maxLength = 100) {
  return content.length > maxLength ? `${content.substring(0, maxLength)}...` : content;
}

// 批量选择状态
const selectedItems = ref<string[]>([]);

// 全选/取消全选
function toggleSelectAll() {
  if (selectedItems.value.length === filteredList.value.length) {
    selectedItems.value = [];
  } else {
    selectedItems.value = filteredList.value.map(item => item.id);
  }
}

// 批量审核操作
function handleBatchAudit(action: TaskStatus.COMPLETED | TaskStatus.REJECTED) {
  selectedItems.value.forEach((id) => {
    handleAudit(id, action);
  });
  selectedItems.value = []; // 清空选择
}

// 拒绝理由相关状态
const rejectReason = ref('');
const showRejectDialog = ref(false);
const currentRejectId = ref('');
// 分页
const pagination = ref({
  pageNum: 1,
  pageSize: 5,
  hasMore: true, // 添加是否有更多数据的标志
});

// 获取审核列表
async function fetchAuditList(isLoadMore = false) {
  if (!isLoadMore) {
    pagination.value.pageNum = 1;
    pagination.value.hasMore = true;
  }

  const query = {
    ...pagination.value,
    auditType: activeTab.value === AuditType.ARTICLE ? AuditType.ARTICLE : AuditType.COMMENT,
    status: TaskStatus.PROCESSING,
  };

  const res = await getAuditTaskPage(query);

  if (isLoadMore) {
    auditList.value = [...auditList.value, ...res.list.map(mapItemToAuditItem)];
  } else {
    auditList.value = res.list.map(mapItemToAuditItem);
  }

  pagination.value.hasMore = res.list.length >= pagination.value.pageSize;
  if (isLoadMore) {
    pagination.value.pageNum++;
  }
}

// 映射数据
function mapItemToAuditItem(item) {
  return {
    id: item.id.toString(),
    type: item.auditType,
    title: item.auditType === AuditType.ARTICLE ? '文章标题' : '评论内容',
    content: item.blogContent,
    author: item.author,
    avatar: item.avatar,
    createTime: item.createTime,
    status: item.status,
    rejectReason: item.rejectReasons,
  };
}

// 加载更多
function loadMore() {
  if (pagination.value.hasMore) {
    fetchAuditList(true);
  }
}

// 审核通过
async function handleAudit(id: string, action: TaskStatus.COMPLETED | TaskStatus.REJECTED) {
  if (action === TaskStatus.COMPLETED) {
    await approveAuditTask(Number(id));
    const item = auditList.value.find(item => item.id === id);
    if (item) {
      item.status = TaskStatus.COMPLETED;
    }
  } else {
    currentRejectId.value = id;
    showRejectDialog.value = true;
  }
}

// 确认拒绝
async function confirmReject() {
  await rejectAuditTask(Number(currentRejectId.value), rejectReason.value);
  const item = auditList.value.find(item => item.id === currentRejectId.value);
  if (item) {
    item.status = TaskStatus.REJECTED;
    item.rejectReason = rejectReason.value;
  }
  rejectReason.value = '';
  showRejectDialog.value = false;
}
</script>

<template>
  <view class="min-h-screen bg-gray-50 p-4">
    <!-- 选项卡 -->
    <view class="flex justify-center mb-6">
      <view class="flex bg-white rounded-lg shadow-sm overflow-hidden border border-gray-200">
        <view
          v-for="tab in ['ARTICLE', 'COMMENT']"
          :key="tab"
          class="px-6 py-2 cursor-pointer transition-colors duration-200"
          :class="{
            'bg-gradient-to-r from-blue-500 to-blue-400 text-white shadow-inner': activeTab === tab,
            'text-gray-600 hover:bg-gray-50': activeTab !== tab,
          }"
          @click="activeTab = tab as AuditType"
        >
          <text class="font-medium text-sm">
            {{ tab === 'ARTICLE' ? '文章审核' : '评论审核' }}
          </text>
        </view>
      </view>
    </view>

    <!-- 批量操作栏 -->
    <view
      v-if="filteredList.length > 0"
      class="flex items-center justify-between mb-4 p-3 bg-white rounded-lg shadow-sm border border-gray-100 transition-all duration-200"
      :class="{
        'bg-blue-50 border-blue-100': selectedItems.length > 0,
      }"
    >
      <view class="flex items-center">
        <checkbox
          :checked="selectedItems.length === filteredList.length"
          class="transform scale-90"
          @click="toggleSelectAll"
        />
        <text class="ml-2 text-sm text-gray-600">
          全选
        </text>
        <text
          class="ml-2 text-sm"
          :class="{
            'text-blue-500 font-medium': selectedItems.length > 0,
            'text-gray-500': selectedItems.length === 0,
          }"
        >
          已选 {{ selectedItems.length }} 项
        </text>
      </view>
      <view class="flex space-x-2">
        <button
          v-if="selectedItems.length > 0"
          class="px-3 py-1 bg-gradient-to-r from-green-500 to-green-400 text-white rounded text-sm shadow-sm hover:shadow-md transition-all duration-200 flex items-center"
          @click="handleBatchAudit(TaskStatus.COMPLETED)"
        >
          <Iconify icon="i-mdi-check" size="16" class="mr-1" />
          通过
        </button>
        <button
          v-if="selectedItems.length > 0"
          class="px-3 py-1 bg-gradient-to-r from-red-500 to-red-400 text-white rounded text-sm shadow-sm hover:shadow-md transition-all duration-200 flex items-center"
          @click="handleBatchAudit(TaskStatus.REJECTED)"
        >
          <Iconify icon="i-mdi-close" size="16" class="mr-1" />
          拒绝
        </button>
      </view>
    </view>

    <!-- 空状态 -->
    <view v-if="filteredList.length === 0" class="flex flex-col items-center justify-center py-12">
      <Iconify icon="i-mdi-file-document-outline" size="48" class="text-gray-300 mb-4" />
      <text class="text-gray-500">
        暂无待审核内容
      </text>
    </view>

    <!-- 审核列表 -->
    <view class="space-y-4">
      <view
        v-for="item in filteredList"
        :key="item.id"
        class="bg-white rounded-lg shadow-sm p-4 border border-gray-100 hover:shadow-md transition-all duration-200"
      >
        <!-- 选择框 -->
        <view class="flex justify-end mb-2">
          <checkbox
            :checked="selectedItems.includes(item.id)"
            class="transform scale-90"
            @click="selectedItems.includes(item.id)
              ? selectedItems = selectedItems.filter(id => id !== item.id)
              : selectedItems.push(item.id)"
          />
        </view>

        <!-- 作者信息 -->
        <view class="flex items-center mb-3">
          <image
            :src="item.avatar || 'https://pic1.zhimg.com/80/v2-6afa72220d29f045c15217aa6b275808_720w.webp'"
            class="w-8 h-8 rounded-full mr-2 border border-gray-200"
          />
          <text class="text-sm text-gray-700 font-medium">
            {{ item.author }}
          </text>
          <text class="text-xs text-gray-400 ml-2">
            {{ formatTimeAgo(item.createTime) }}
          </text>
        </view>

        <!-- 标题和状态 -->
        <view class="flex justify-between items-start mb-2">
          <text class="text-lg font-semibold text-gray-800 line-clamp-2">
            {{ item.title }}
          </text>
          <view class="flex items-center">
            <view
              class="px-2 py-1 rounded-full text-xs"
              :class="{
                'bg-yellow-100 text-yellow-700': item.status === TaskStatus.PROCESSING,
                'bg-green-100 text-green-700': item.status === TaskStatus.COMPLETED,
                'bg-red-100 text-red-700': item.status === TaskStatus.REJECTED,
              }"
            >
              {{
                item.status === TaskStatus.PROCESSING ? '待审核'
                : item.status === TaskStatus.COMPLETED ? '已通过' : '已拒绝'
              }}
            </view>
          </view>
        </view>

        <!-- 内容预览 -->
        <view class="mb-3">
          <text class="text-gray-600 leading-relaxed line-clamp-3">
            {{ truncateContent(item.content) }}
          </text>
        </view>

        <!-- 操作按钮 -->
        <view v-if="item.status === TaskStatus.PROCESSING" class="flex justify-between space-x-2 mt-3">
          <button
            class="flex-1 px-3 py-2 bg-gradient-to-r from-green-500 to-green-400 text-white rounded-lg hover:shadow-md transition-all duration-200 flex items-center justify-center"
            @click="handleAudit(item.id, TaskStatus.COMPLETED)"
          >
            <Iconify icon="i-mdi-check" size="18" class="mr-1" />
            <text class="text-sm font-medium">
              通过
            </text>
          </button>
          <button
            class="flex-1 px-3 py-2 bg-gradient-to-r from-red-500 to-red-400 text-white rounded-lg hover:shadow-md transition-all duration-200 flex items-center justify-center"
            @click="handleAudit(item.id, TaskStatus.REJECTED)"
          >
            <Iconify icon="i-mdi-close" size="18" class="mr-1" />
            <text class="text-sm font-medium">
              拒绝
            </text>
          </button>
        </view>

        <!-- 拒绝理由 -->
        <view v-if="item.status === TaskStatus.REJECTED && item.rejectReason" class="mt-3 p-2 bg-red-50 rounded text-sm text-red-600">
          <text class="font-medium">
            拒绝理由：
          </text>
          <text>{{ item.rejectReason }}</text>
        </view>
      </view>
    </view>

    <!-- 加载更多提示 -->
    <view v-if="pagination.hasMore" class="flex justify-center py-4">
      <text class="text-gray-500">
        加载中...
      </text>
    </view>
    <view v-else-if="filteredList.length > 0" class="flex justify-center py-4">
      <text class="text-gray-500">
        没有更多数据了
      </text>
    </view>

    <!-- 拒绝理由弹窗 -->
    <view v-if="showRejectDialog" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <view class="bg-white rounded-lg p-5 w-4/5 max-w-md animate-fade-in">
        <view class="mb-4 flex items-center">
          <Iconify icon="i-mdi-alert-circle-outline" size="24" class="text-red-500 mr-2" />
          <text class="text-lg font-semibold text-gray-800">
            请输入拒绝理由
          </text>
        </view>
        <textarea
          v-model="rejectReason"
          class="w-full border border-gray-300 rounded-lg p-3 mb-4 focus:border-blue-500 focus:ring-1 focus:ring-blue-200 transition-all duration-200"
          placeholder="请填写拒绝理由..."
          rows="4"
          auto-focus
        />
        <view class="flex justify-end space-x-3">
          <button
            class="w-24 py-2 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300 transition-colors duration-200"
            @click="showRejectDialog = false"
          >
            取消
          </button>
          <button
            class="w-24 py-2 bg-gradient-to-r from-red-500 to-red-400 text-white rounded-lg hover:shadow-md transition-all duration-200"
            :class="{ 'opacity-70 cursor-not-allowed': !rejectReason }"
            :disabled="!rejectReason"
            @click="confirmReject"
          >
            确认
          </button>
        </view>
      </view>
    </view>
  </view>
</template>

<style lang="scss" scoped>
.line-clamp-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.line-clamp-3 {
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.animate-fade-in {
  animation: fadeIn 0.3s ease-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>
